/**
 * 交互指令处理
 * 普通div元素时，正常绑定事件
 * 组件元素时，只处理.native
 * @author tsdy
 * v-on:
 * @
 */
import { Pixijsvue } from "../main";
import { Scope } from "../../typings/traverse";
import { Container, InteractionEvent } from "pixi.js";
import {
  getGoalData,
  absolutePath,
  checkNamespace,
  getInteractiveAttribute,
  parseFunctionArgvs,
  parseFunctionName
} from "../../utils/index";
const interactive = [
  "click",
  "mousedown",
  "mousemove",
  "mouseout",
  "mouseover",
  "mouseup",
  "mouseupoutside",
  "rightclick",
  "rightdown",
  "rightup",
  "rightupoutside",
  "tap",
  "touchcancel",
  "touchend",
  "touchendoutside",
  "touchmove",
  "touchstart"
];

function disposeInteractive(
  that: Pixijsvue,
  $data: Record<string, any>,
  $methods: Record<string, Function>,
  container: Container,
  element: Element,
  scope: Scope | undefined,
  isComponent: boolean
) {
  interactive.forEach((item) => {
    
    let hasAttribute: boolean = false;
    if (isComponent) {
      if (element.hasAttribute(`@${item}.native`) ||
      element.hasAttribute(`v-on:${item}.native`)) {
        hasAttribute = true;
      }
    } else {
      if (element.hasAttribute(`@${item}`) ||
      element.hasAttribute(`v-on:${item}`)) {
        hasAttribute = true;
      }
    }
    if (hasAttribute) {
      container.interactive = true;
      let v_on = <string>getInteractiveAttribute(element, item);
      /**
       * 去除括号，和括号里的字符串
       * functionName(item)
       */
      let v_onPath = parseFunctionName(v_on);
      let _argvs: Array<string> | undefined;
      _argvs = parseFunctionArgvs(v_on);
      /**
       * _argvs是参数名数组。
       * argvs是参数名对应的数据
       */
      container.addListener(item, (e: InteractionEvent) => {
        e.data.target = <PIXI.Sprite>container;
        if (_argvs) {
          let argvs: Array<any>;
          if (scope) {
            const { items, item } = scope;
            argvs = _argvs.map((argv) => {
              if (argv == "$event") {
                return e;
              } else {
                let isArgvNamespace = checkNamespace(argv, item);
                if (isArgvNamespace) {
                  return getGoalData(
                    $data,
                    absolutePath(items, item, argv)
                  );
                } else {
                    return getGoalData($data, argv);
                }
              }
            });
          } else {
            argvs = _argvs.map((argv) => {
              if (argv == "$event") {
                return e;
              } else {
                return getGoalData($data, argv);
              }
            });
          }
          $methods[v_onPath].apply(that, argvs);
        } else {
          $methods[v_onPath].call(that);
        }
      });
    }
  });
}

export { disposeInteractive };
